package com.jumi.microservice.service.admin;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.base.dto.ExportExcelCommonResponse;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.utils.EnumUtil;
import com.jumi.microservice.dto.afterseal.AdminAfterSaleRequest;
import com.jumi.microservice.dto.afterseal.AfterSaleGoodsInfo;
import com.jumi.microservice.dto.logistics.SupplyListResponse;
import com.jumi.microservice.entity.AfterSealOrder;
import com.jumi.microservice.entity.AfterSealOrderGoods;
import com.jumi.microservice.enumerate.LogisticsStatusEnum;
import com.jumi.microservice.enumerate.SelfFlagEnum;
import com.jumi.microservice.mapper.AfterSealOrderGoodsMapper;
import com.jumi.microservice.mapper.AfterSealOrderMapper;
import com.jumi.microservice.material.dto.supplier.JmSupplierResponse;
import com.jumi.microservice.material.dto.warehouse.JmWarehouseResponse;
import com.jumi.microservice.material.service.IJmSupplierService;
import com.jumi.microservice.material.service.IJmWarehouseService;
import com.jumi.microservice.service.IUserExternalService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by mazhao
 * @Classname AdminSelfListService
 * @Description TODO
 * @Date 2020/10/6 15:48
 */
@Service
public class AdminExcelService {
    @Resource
    AfterSealOrderMapper afterSealOrderMapper;
    @Resource
    AfterSealOrderGoodsMapper afterSealOrderGoodsMapper;
    @DubboReference
    IJmWarehouseService iWarehouseService;
    @DubboReference
    IJmSupplierService iSupplyService;
    @Resource
    AdminSendService adminSendService;
    @DubboReference
    private IUserExternalService iUserExternalService;

    /**
     * 自营或非自营导出
     *
     * @param status
     * @param self
     * @return
     */
    public ExportExcelCommonResponse<AfterSaleGoodsInfo> excelExport(AdminAfterSaleRequest request, String filename, List<Byte> status, Byte... self) {
        ExportExcelCommonResponse exportExcelCommonResponse = new ExportExcelCommonResponse();
        QueryWrapper<AfterSealOrderGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0).in("goods_status", status).in("self_flag", self)
                .orderByDesc("create_time");
        if (request.getOrderNo() != null && !request.getOrderNo().trim().isEmpty()) {
            QueryWrapper<AfterSealOrder> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("order_no", request.getOrderNo());
            AfterSealOrder afterSealOrder = afterSealOrderMapper.selectOne(queryWrapper1);
            queryWrapper.eq("order_id", afterSealOrder.getId());
        }
        if (request.getWarehouseId() != null) {
            queryWrapper.eq("warehouse", request.getWarehouseId());
        }
        if (request.getSupplierId() != null) {
            queryWrapper.eq("supplier_id", request.getSupplierId());
        }
        if (request.getGoodsName() != null && !request.getGoodsName().trim().isEmpty()) {
            queryWrapper.like("goods_name", request.getGoodsName());
        }
        if (request.getStartTime() != null) {
            queryWrapper.ge("create_time", request.getStartTime()).le("create_time", request.getEndTime());
        }
        if (request.getIds() != null && !request.getIds().trim().isEmpty()) {
            queryWrapper.in("order_id", request.getIds());
        }
        List<Integer> ids = new ArrayList<>();
        if (request.getBuyerPhone() != null && !request.getBuyerPhone().trim().isEmpty()) {
            Integer uid = iUserExternalService.getUidByMobile(request.getBuyerPhone());
            QueryWrapper<AfterSealOrder> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("del_flag", DelFlag.NORMAL);
            if (uid != null && uid > 0) {
                queryWrapper1.eq("buyer_id", uid);
            } else {
                queryWrapper1.eq("buyer_id", DelFlag.NORMAL);
            }
            ids = afterSealOrderMapper.selectList(queryWrapper1).stream().map(AfterSealOrder::getId).collect(Collectors.toList());
        }
        if (request.getReceiverPhone() != null && !request.getReceiverPhone().trim().isEmpty()) {
            QueryWrapper<AfterSealOrder> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("receiver_phone", request.getReceiverPhone()).eq("del_flag", 0);
            ids = afterSealOrderMapper.selectList(queryWrapper1).stream().map(AfterSealOrder::getId).collect(Collectors.toList());
        }
        if (!ids.isEmpty()) {
            queryWrapper.in("order_id", ids);
        }
        List<AfterSaleGoodsInfo> result = new ArrayList<>();
        if (ids.isEmpty() && (request.getBuyerPhone() != null || request.getReceiverPhone() != null)) {
            exportExcelCommonResponse.setData(result);
            exportExcelCommonResponse.setFileName(filename);
            return exportExcelCommonResponse;
        }
        List<AfterSealOrderGoods> list = afterSealOrderGoodsMapper.selectList(queryWrapper);
        List<Integer> orderIds = list.stream().map(AfterSealOrderGoods::getOrderId).collect(Collectors.toList());
        Map<Integer, AfterSealOrder> orderInfoMap = getOrderInfo(orderIds);
        Map<Integer, String> warehouseMap = getWarehouseInfo();
        Map<Integer, String> supplyMap = supplyInfo();
        for (AfterSealOrderGoods afterSealOrderGoods : list) {
            AfterSaleGoodsInfo afterSaleGoodsInfo = new AfterSaleGoodsInfo();
            BeanUtils.copyProperties(afterSealOrderGoods, afterSaleGoodsInfo);
            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(afterSealOrderGoods.getGoodsStatus(), LogisticsStatusEnum.class);
            afterSaleGoodsInfo.setGoodsStatus(logisticsStatusEnum.getMsg());
            if(afterSealOrderGoods.getSelfFlag().equals(SelfFlagEnum.YES_SELF.getCode())){
                afterSaleGoodsInfo.setName("");
                if (warehouseMap.containsKey(afterSealOrderGoods.getWarehouse())) {
                    afterSaleGoodsInfo.setName(warehouseMap.get(afterSealOrderGoods.getWarehouse()));
                }
            }else{
                afterSaleGoodsInfo.setName("");
                if(supplyMap.containsKey(afterSealOrderGoods.getSupplierId())){
                    afterSaleGoodsInfo.setName(supplyMap.get(afterSealOrderGoods.getSupplierId()));
                }
            }
            if (orderInfoMap.containsKey(afterSealOrderGoods.getOrderId())) {
                afterSaleGoodsInfo.setBuyerId(orderInfoMap.get(afterSealOrderGoods.getOrderId()).getBuyerId());
                afterSaleGoodsInfo.setOriginalOrderNo(orderInfoMap.get(afterSealOrderGoods.getOrderId()).getOriginalOrderNo());
                afterSaleGoodsInfo.setOrderNo(orderInfoMap.get(afterSealOrderGoods.getOrderId()).getOrderNo());
                afterSaleGoodsInfo.setReceiverInfo(orderInfoMap.get(afterSealOrderGoods.getOrderId()).getReceiverName()
                        + "\r\n" + orderInfoMap.get(afterSealOrderGoods.getOrderId()).getReceiverPhone()
                        + "\r\n" + orderInfoMap.get(afterSealOrderGoods.getOrderId()).getReceiverAddress());
            }
            result.add(afterSaleGoodsInfo);
        }
        exportExcelCommonResponse.setData(result);
        exportExcelCommonResponse.setFileName(filename);
        return exportExcelCommonResponse;
    }

    /**
     * 售后自营待发货导入
     *
     * @param request
     * @param uid
     * @param name
     * @return
     * @throws IOException
     */
    public List<String> sendExcelImport(HttpServletRequest request, Long uid, String name) throws IOException {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(request.getInputStream(), AfterSaleGoodsInfo.class, new SendListener(adminSendService, uid, name)).sheet().doRead();
        return AdminSendService.importError;
    }

    /**
     * 获取订单编号
     *
     * @param orderIds
     * @return
     */
    public Map<Integer, AfterSealOrder> getOrderInfo(List<Integer> orderIds) {
        if (orderIds.isEmpty()) {
            return null;
        }
        QueryWrapper<AfterSealOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", orderIds);
        List<AfterSealOrder> list = afterSealOrderMapper.selectList(queryWrapper);
        Map<Integer, AfterSealOrder> map = new HashMap<>(list.size());
        for (AfterSealOrder afterSealOrder : list) {
            map.put(afterSealOrder.getId(), afterSealOrder);
        }
        return map;
    }

    /**
     * 获取全部仓库信息
     *
     * @return
     */
    public Map<Integer, String> getWarehouseInfo() {
        List<JmWarehouseResponse> list = iWarehouseService.findAll().getData();
        Map<Integer, String> map = new HashMap<>(list.size());
        for (JmWarehouseResponse jmWarehouseResponse : list) {
            map.put(jmWarehouseResponse.getWarehouseId().intValue(), jmWarehouseResponse.getWarehouseName());
        }
        return map;
    }

    /**
     * 供应商列表
     *
     * @return
     */
    public Map<Integer, String> supplyInfo() {
        List list = iSupplyService.list().getData();
        Map<Integer, String> map = new HashMap<>(list.size());
        for (Object object : list) {
            JmSupplierResponse jmSupplierResponse = JSON.parseObject(JSON.toJSONString(object), JmSupplierResponse.class);
            map.put(jmSupplierResponse.getSupplierId().intValue(), jmSupplierResponse.getSupplierCompanyName());
        }
        return map;
    }
}
